package com.kantboot.project.file.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.kantboot.project.file.config.OSSConfig;
import com.kantboot.project.file.entity.CesOssPolicy;
import com.kantboot.project.file.service.IPolicyService;
import com.kantboot.project.security.entity.SysUser;
import com.kantboot.project.security.service.ISysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class PolicyServiceImpl implements IPolicyService {

    @Resource
    private OSS oss;

    @Resource
    OSSConfig ossConfig;

    @Resource
    private ISysUserService sysUserService;

    @Override
    public CesOssPolicy create(){

        SysUser userInfo = this.sysUserService.getUserInfo();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
        String uuid = UUID.randomUUID().toString().replace("-","");
        // 设置上传到OSS文件的前缀，可置空此项。置空后，文件将上传至Bucket的根目录下。
        String dir = format+"/"+userInfo.getId()+"-"+uuid;

        // 设置过期时间
        long expireTime = 30;
        long expireEndTime
                = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime);

        // PostObject 请求最大可支持的文件大小为 5GB，即 CONTENT_LENGTH_RANGE 为 5*1024*1024*1024。
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
        String postPolicy = oss.generatePostPolicy(expiration, policyConds);
        byte[] binaryData = new byte[0];
        try {
            binaryData = postPolicy.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = oss.calculatePostSignature(postPolicy);

        CesOssPolicy cesOssPolicy=
                new CesOssPolicy()
                        .setAccessId(ossConfig.getAccessKeyId())
                        .setPolicy(encodedPolicy)
                        .setSignature(postSignature)
                        .setDir(dir)
                        .setHost(ossConfig.getHost())
                        .setExpire(String.valueOf(expireEndTime / 1000));

        JSONObject jasonCallback = new JSONObject();

        //添加回调地址
        jasonCallback.put("callbackUrl", ossConfig.getCallbackUrl());
        jasonCallback.put("callbackBody",
                "filename=${object}" +
                        "&size=${size}" +
                        "&mimeType=${mimeType}" +
                        "&height=${height}" +
                        "&width=${width}" +
                        "&userId="+userInfo.getId());
        jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
        String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
        cesOssPolicy.setCallback(base64CallbackBody);

        return cesOssPolicy;
    }

    /**
     * 私有文件生成临时访问路径
     * @param key 访问文件 实例(20220331/2f5837e548674a288f6ecdbb2f0012dc.jpg)
     * @return
     */
    @Override
    public  String createFileTemporaryUrl(String key){
        // 设置URL过期时间为1小时
        Date expiration = new Date(new Date().getTime() + 1000 * 30);
//        GeneratePresignedUrlRequest generatePresignedUrlRequest =
//                new GeneratePresignedUrlRequest(ossConfig.getBucketName(), key);
//        generatePresignedUrlRequest.setExpiration(expiration);

        URL url = oss
                .generatePresignedUrl(ossConfig.getBucketName(),
                key,expiration);
        return url.toString();
    }

}
